package com.bitin.adorn.common.payload;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;

import java.io.Serializable;

/**
 * 统一返回数据结构
 *
 * @author Mr.Lu
 * @since 2024/10/12 9:12
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
    private String code;
    private String message;
    private T data;

    public static <T> ApiResult<T> success() {
        return success(null);
    }

    public static <T> ApiResult<Pagination<T>> paging(Page<T> page) {
        return success(Pagination.paging(page));
    }

    public static <T> ApiResult<T> success(T data) {
        return instance(ApiResultCode.SUCCESS.getCode(), ApiResultCode.SUCCESS.getMessage(), data);
    }

    public static ApiResult<?> failed() {
        return instance(ApiResultCode.SYSTEM_ERROR.getCode(), ApiResultCode.SYSTEM_ERROR.getMessage(), null);
    }

    public static ApiResult<?> failed(String message) {
        return instance(ApiResultCode.SYSTEM_ERROR.getCode(), message, null);
    }

    public static ApiResult<?> failed(IResultCode iResultCode) {
        return instance(iResultCode.getCode(), iResultCode.getMessage(), null);
    }

    public static ApiResult<?> failed(IResultCode iResultCode, String message) {
        return instance(iResultCode.getCode(), StringUtils.isNotBlank(message) ? message : iResultCode.getMessage(), null);
    }

    public static ApiResult<?> judge(boolean status) {
        if (status) {
            return success();
        } else {
            return failed();
        }
    }

    private static <T> ApiResult<T> instance(IResultCode iResultCode, T data){
        return instance(iResultCode.getCode(), iResultCode.getMessage(), data);
    }

    private static <T> ApiResult<T> instance(String code, String message, T data){
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.setCode(code);
        apiResult.setMessage(message);
        apiResult.setData(data);
        return apiResult;
    }

    public static boolean isSuccess(ApiResult<?> result) {
        return result != null && ApiResultCode.SUCCESS.getCode().equals(result.getCode());
    }
}
